package org.ruixue.config.datasource;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.jdbc.DataSourceBuilder;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
 
import javax.sql.DataSource;
 
@Configuration
@MapperScan(basePackages = "org.ruixue.dao.yshop", sqlSessionFactoryRef = "yshopSqlSessionFactory")
public class YshopDataSourceConfig {
	
    @Bean(name = "yshopDataSource")
    @ConfigurationProperties(prefix = "spring.datasource.yshop")
    public DataSource getYshopDateSource()
    {
        return DataSourceBuilder.create().build();
    }
 
    @Bean(name = "yshopSqlSessionFactory")
    public SqlSessionFactory yshopSqlSessionFactory(@Qualifier("yshopDataSource") DataSource datasource)
            throws Exception
    {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(datasource);
        bean.setMapperLocations(
                new PathMatchingResourcePatternResolver().getResources("classpath*:mapper/yshop/*.xml"));
        return bean.getObject();
    }
 
    @Bean("yshopSqlSessionTemplate")
    public SqlSessionTemplate yshopSqlSessionTemplate(
            @Qualifier("yshopSqlSessionFactory") SqlSessionFactory sessionFactory)
    {
        return new SqlSessionTemplate(sessionFactory);
    }
}